package cn.git.shiro.util;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @description: jwt工具类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-27
 */
@Component
public class JWTUtil {

    /**
     * 自定义jwt密钥
     */
    @Value("${custom.jwt.secret}")
    private String secret;

    /**
     * jwt过期时间
     * 单位秒
     */
    @Value("${custom.jwt.expire}")
    private long expire;

    /**
     * 创建jwt
     * @param username 用户名
     * @param customClaimsMap 自定义jwt键值对
     * @return
     */
    public String createJWTToken(String username, Map<String, String> customClaimsMap) {
        // 创建jwt构造器
        JWTCreator.Builder builder = JWT.create();
        if (ObjectUtil.isNotEmpty(customClaimsMap)) {
            // 设置自定义值信息
            customClaimsMap.forEach(builder::withClaim);
        }

        // 使用HS256算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 设置过期时间，单位秒
        Date expireDate = new Date(System.currentTimeMillis() + expire * 1000);

        return builder
                .withExpiresAt(expireDate)
                .sign(algorithm);
    }

    /**
     * 判断jwt是否过期
     * @param token
     * @return
     */
    public boolean ifTokenExpire(String token) {
       try {
           DecodedJWT decode = JWT.decode(token);
           return decode.getExpiresAt().before(new Date());
       } catch (Exception e) {
           throw new RuntimeException("传入token解析失败,请确认!");
       }
    }

    /**
     * 验证jwt
     * @param token
     * @return
     */
    public boolean verifyJWTToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取jwt自定义值
     * @param token
     * @param key
     * @return
     */
    public String getCustomClaim(String token, String key) {
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim(key).asString();
        } catch (Exception e) {
            return null;
        }
    }

}
